﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Speech.Synthesis;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace ReadTxT
{
    public partial class Form1 : Form
    {



        public Form1()
        {
            InitializeComponent();
        }
        SpeechSynthesizer voice = new SpeechSynthesizer();   //创建语音实例
        string readTitle = "Xujoe";
        private void button1_Click(object sender, EventArgs e)
        {
            voice.SpeakAsyncCancelAll();  //取消朗读

            ReadTextStart(ktxt);

        }

        private void ReadTextStart(Dictionary<string, string> ktxt)
        {

            if (ktxt == null || ktxt.Count == 0 || checkBox2.Checked == false)
            {
                string s = textBox1.Text;
                if (ktxt != null && ktxt.Count != 0)
                {
                    ktxt.TryGetValue(listBox1.SelectedItem.ToString(), out s);

                }

                ReadTextContent(s);
            }
            else
            {
                string str = "";
                for (int i = 0; i < listBox1.Items.Count; i++)
                {

                    if (i >= listBox1.SelectedIndex)
                    {
                        string s = "";
                        ktxt.TryGetValue(listBox1.Items[i].ToString(), out s);
                        str = str + listBox1.Items[i].ToString() + "\r\n" + s;
                    }

                    if (i+1 >= listBox1.SelectedIndex + numericUpDown4.Value)
                    {
                        break;
                    }

                }


                ReadTextContent(str);

            }
        }

        private void ReadTextContent(string str)
        {
            textBox1.Text = str;
            textBox1.Tag = str;
            button9.Text = "正在读的";
            readTitle = this.Text;//现在阅读的标题
            var yiju = str.Split(new char[] { '。', '?', '!', '？', '！' });
            SetControlText(label3, yiju.Length.ToString());
            var t = new Thread(x =>
            {
                try
                {

                    foreach (var item in yiju)
                    {

                        SetControlText(textBox2, item);
                        if (form != null && !form.IsDisposed)
                        {
                            SetControlText(form.label_Word, item);

                        }
                        voice.Speak(item);

                    }

                    SetControlText(button9, "已读完");
                }
                catch (Exception eeee)
                {
                    SetControlText(label7, eeee.Message);

                }
                finally
                {

                }
            });
            t.Name = "ReadThread";
            t.IsBackground = true;
            t.Start();

        }
        //*********************线程中绑定数据***********************//
        public void SetControlText(Control control, string s)
        {
            control.Invoke(new MethodInvoker(delegate ()
            {
                control.Text = s;
            }));
        }


        private void button3_Click(object sender, EventArgs e)
        {
            voice.Pause();  //暂停朗读
        }

        private void button2_Click(object sender, EventArgs e)
        {
            voice.Resume(); //继续朗读
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            voice.Rate = int.Parse(numericUpDown1.Value.ToString()); //设置语速,[-10,10]
        }

        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {
            voice.Volume = int.Parse(numericUpDown2.Value.ToString()); ; //设置音量,[0,100]
        }

        private void button4_Click(object sender, EventArgs e)
        {
            voice.SpeakAsyncCancelAll();  //取消朗读
        }
        int index = 0;
        private void button5_Click(object sender, EventArgs e)
        {

            textBox1.Focus();
            textBox1.SelectionStart = index;  //设置起始位置 
            textBox1.SelectionLength = 36;  //设置长度
            index = textBox1.SelectionStart + textBox1.SelectionLength;
            textBox1.ScrollToCaret();


            //  textBox1.Select(3, 6);
        }
        Dictionary<string, string> ktxt;
        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "文本文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                label_file.Text = file;
                ktxt = GetTitle(ReadTxtContent(file));

                listBox1.Items.Clear();
                foreach (var item in ktxt.Keys)
                {
                    listBox1.Items.Add(item);

                }
            }





        }


        Dictionary<string, string> GetTitle(String baseTxt)
        {

            List<string> allTitle = new List<string>();
            List<int> keyNum = new List<int>();
            Dictionary<string, string> keyTxtDic = new Dictionary<string, string>();
            Regex reg = new Regex("(第.*?章.*?)\r\n");
            MatchCollection mcs = reg.Matches(baseTxt.Trim());
            string[] newArray = reg.Split(baseTxt.Trim());
            allTitle.Add("第一个去掉0位---");

            for (int i = 1; i < newArray.Length; i += 2)
            {
                keyTxtDic.Add(newArray[i].Trim(), newArray[i + 1]);
            }


            return keyTxtDic;

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectTitle = listBox1.SelectedItem.ToString();
            if (ktxt.TryGetValue(selectTitle, out string value))
            {
                textBox1.Text = selectTitle + "\r\n" + value;
                this.Text = selectTitle;

            }




        }

        private void button7_Click(object sender, EventArgs e)
        {
            SaveTxtLine("进度" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "进度", "./data");
            SaveTxtLine(label_file.Text, "进度", "./data");
            SaveTxtLine(listBox1.SelectedItem.ToString(), "进度", "./data");
            label7.Text = "记录保存成功";
        }


        /// <summary>
        /// 写入文本
        /// </summary>
        /// <param name="LogLine">新行内容</param>
        /// <param name="name">名字</param>
        /// <param name="path">路径</param>
        public void SaveTxtLine(string LogLine, string name, string path)
        {



            //生成目录
            //创建文件夹
            if (Directory.Exists(path) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(path);
            }

            // 判断文件是否存在，不存在则创建，否则读取值显示到txt文档
            if (!System.IO.File.Exists(path + "/" + name + "_" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt"))
            {
                FileStream fs1 = new FileStream(path + "/" + name + "_" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt", FileMode.Create, FileAccess.Write);//创建写入文件 
                StreamWriter sw = new StreamWriter(fs1);
                sw.WriteLine(LogLine);//开始写入值
                sw.Close();
                fs1.Close();
            }
            else
            {
                FileStream fs = new FileStream(path + "/" + name + "_" + DateTime.Today.ToString("yyyy-MM-dd") + ".txt" + "", FileMode.Append, FileAccess.Write);
                StreamWriter sr = new StreamWriter(fs);
                sr.WriteLine(LogLine);//开始写入值
                sr.Close();
                fs.Close();
            }

        }
        /// <summary>
        /// 读取txt文件内容
        /// </summary>
        /// <param name="Path">文件地址</param>
        public string ReadTxtContent(string Path)
        {
            try
            {
                StreamReader sr = new StreamReader(Path, Encoding.UTF8);
                string content;
                string allcontent = "";

                while ((content = sr.ReadLine()) != null)
                {
                    // textBox2.AppendText(content.ToString() + "\r\n");
                    allcontent += content.ToString() + "\r\n";
                }
                return allcontent;
            }
            catch
            {

                return null;
            }



        }

        private void button8_Click(object sender, EventArgs e)
        {

            label7.Text = "请稍等，文件越大读取越慢";

            DirectoryInfo folder = new DirectoryInfo("./data");
            List<string> fileName = new List<string>();
            var last = "1997-02-03".Split('-');
            foreach (FileInfo file in folder.GetFiles("*.txt"))
            {
                Console.WriteLine(file.Name);
                if (file.Name.Length == 17) //进度_2020 - 04 - 01.txt
                {
                    var str = file.Name.Split(new char[2] { '_', '.' });
                    var date = str[1].Split('-');
                    #region 判断最大的日期赋值给last
                    if (int.Parse(date[0]) > int.Parse(last[0]))
                    {
                        last = date;
                    }
                    else
                    {
                        if (int.Parse(date[1]) > int.Parse(last[1]))
                        {
                            last = date;
                        }

                        else
                        {
                            if (int.Parse(date[2]) > int.Parse(last[2]))
                            {
                                last = date;
                            }
                        }
                    }

                    #endregion


                }


            }

            var s = ReadTxtContent($"./data/进度_{last[0]}-{last[1]}-{last[2]}.txt");

            Regex reg = new Regex("\r\n");

            var da = reg.Split(s.Trim());
            var path = da[da.Length - 2];
            var title = da[da.Length - 1];

            if (!path.Equals(label_file.Text))
            {
                ktxt = GetTitle(ReadTxtContent(path));
            }
            listBox1.Items.Clear();
            foreach (var item in ktxt.Keys)
            {
                listBox1.Items.Add(item);

            }
            listBox1.SelectedItem = title;
            label7.Text = "提取进度成功";
            label_file.Text = path;
        }

        string familyfont = "幼圆";
        float fontsize = 12F;
        private void numericUpDown3_ValueChanged(object sender, EventArgs e)
        {
            fontsize = (float)numericUpDown3.Value;
            textBox1.Font = new System.Drawing.Font(familyfont, fontsize);
        }

        //获取系统字体方法
        public dynamic GetFontNames()
        {
            FontFamily[] fontFamilies;
            InstalledFontCollection installedFontCollection = new InstalledFontCollection();
            fontFamilies = installedFontCollection.Families;
            return fontFamilies;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            familyfont = comboBox1.SelectedItem.ToString();
            textBox1.Font = new System.Drawing.Font(familyfont, fontsize);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            voice.Rate = 6; //设置语速,[-10,10]
            voice.Volume = 100; //设置音量,[0,100]
            FontFamily[] fontFamilies = GetFontNames();

            for (int i = 0; i < fontFamilies.Length; i++)
            {
                comboBox1.Items.Add(fontFamilies[i].Name);
            }
            comboBox1.SelectedItem = familyfont;




        }

        WordForm form = null;
        private void button5_Click_1(object sender, EventArgs e)
        {
            if (form == null || form.IsDisposed)
            {
                form = new WordForm();
                form.Show();
            }
            form.TopMost = true;


        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

            SwitchState();
        }

        private void 主页ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            SwitchState();
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {

                SwitchState();
            }
        }

        private void SwitchState()
        {
            this.TopMost = true;
            this.WindowState = FormWindowState.Normal;
            this.TopMost = false;


        }
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 关闭悬浮ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (form == null || form.IsDisposed)
            {
                form = new WordForm();
                form.Show();
                form.TopMost = true;
            }
            else
            {
                form.Close();
            }




        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            label7.Text = "字数:" + textBox1.Text.Length.ToString();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Tag.ToString();
        }
    }
}
